package org.darcy.service.flow.impl;

import java.util.Date;

import org.darcy.dao.FlowLeaveCompanyMapper;
import org.darcy.entity.FlowLeaveCompany;
import org.darcy.entity.work.WorkInstance;
import org.darcy.framework.constant.BusinessType;
import org.darcy.framework.constant.SysConstant;
import org.darcy.framework.generic.GenericServiceImpl;
import org.darcy.framework.model.PageData;
import org.darcy.framework.model.PageParam;
import org.darcy.service.flow.FlowLeaveCompanyService;
import org.darcy.service.org.StaffService;
import org.darcy.service.work.WorkService;
import org.darcy.utils.UserTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;


/**
 * FlowLeaveCompany服务实现
 */
@Service
@Transactional
public class FlowLeaveCompanyServiceImpl extends GenericServiceImpl<FlowLeaveCompany> implements FlowLeaveCompanyService{
	
	@Autowired
	private FlowLeaveCompanyMapper mapper;
	
	@Autowired
	private WorkService WorkService;
	
	@Autowired
	private StaffService StaffService;
	
	@Override
	public FlowLeaveCompany getDetail(Integer id) {
		FlowLeaveCompany record = mapper.selectById(id);
		WorkService.processWorkFlowObject(record, SysConstant.FormType.LeaveCompany);
		return record;
	}
	
	@Override
	public int delete(Object id) {
		super.delete(id);
		WorkInstance param = WorkInstance.builder().formId((Integer) id).formType(SysConstant.FormType.LeaveCompany)
				.build();
		WorkInstance work = WorkService.getBusinessWork(param);
		WorkService.delete(work.getId());
		return 1;
	}
	
	@Override
	public PageData<FlowLeaveCompany> page(PageParam param) {
		PageData<FlowLeaveCompany> data = super.getPageData(param);
		return data;
	}
	
	/**
	 * 处理工作任务
	 */
	private void processWork(FlowLeaveCompany record) {
		String name = BusinessType.getBusinessName(SysConstant.FormType.LeaveCompany);
		String staffName = StaffService.getById(record.getLeaveStaffId()).getName();
		String title = String.format("[%s]的%s", staffName, name);
		String time = DateUtil.format(record.getLeaveTime(), "yyyy-MM-dd");
		String summary = String.format("离职人员：%s\n离职时间：%s", staffName, time);
		WorkService.addWorkTask(record, title, summary, SysConstant.FormType.LeaveCompany);
	}

	@Override
	public FlowLeaveCompany insert(FlowLeaveCompany record) {
		record.setCreateTime(new Date());
		// 编号处理
		String time = DateUtil.format(record.getCreateTime(), DatePattern.PURE_DATETIME_FORMATTER);
		record.setFormNo("LZJJ" + time);
		super.insert(record);
		processWork(record);
		return record;
	}

	@Override
	public FlowLeaveCompany update(FlowLeaveCompany record) {
		super.update(record);
		processWork(record);
		return record;
	}

	@Override
	public void doBusiness(Integer id) {
		FlowLeaveCompany record = this.getById(id);
		// TODO staff 更新离职日期等。
		
	}


}
